<template>
    <!-- 查询部分 -->
    <pageTabelLayout>
        <template #pageHeader>
            <div style="float:right">
                <Toolbar :items="['新增', '删除', '保存']" @add="showInsertForm" @del="deleteHandler"
                    @saveData="updateConsumeList"></Toolbar>
            </div>
        </template>

        <template #pageTabel>
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"
                @grid-ready="gridReady" style="height:calc(100% - 45px);" @cell-value-changed="cellValueChange"
                class='ag-theme-alpine' :defaultColDef="defaultColDef" :rowData="tableDataList" :columnDefs="columnDefs"
                :suppressDragLeaveHidesColumns="true" :localeText="localeTextData" :gridOptions="gridOptions">
            </AgGridVuesCopys>
            <paginationCopys :total="searchData.total" show-total style="justify-content: center;margin-bottom:18px"
                @change="pageChange" :current="searchData.current" :page-size="searchData.size"></paginationCopys>
        </template>

        <a-drawer :style="{ 'zIndex': 999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd" unmountOnClose
            @ok="addEquipmentConsume" @cancel="pageData.showAdd = false" cancel-text='关闭' ok-text='保存'>
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" :model="formData" layout="horizontal">
                    <a-form-item label="设备名称" field="meterNo" label-col-flex="100px"
                        :rules="[{ required: true, message: '设备编号必填' }]">
                        <a-select popup-container="html" class="bacClass" placeholder="" v-model="formData.meterNo"
                            allow-clear>
                            <a-option v-for="item in meterList" :value="item.meterNo">
                                {{ item.meterName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="昨日读数" field="lastCount" label-col-flex="100px">
                        <a-input-number v-model="formData.lastCount" :max="99999999" @change="computeUseCount" />
                    </a-form-item>
                    <a-form-item label="今日读数" field="thisCount" label-col-flex="100px">
                        <a-input-number v-model="formData.thisCount" :max="99999999" @change="computeUseCount" />
                    </a-form-item>
                    <a-form-item label="日使用数" field="useCount" label-col-flex="100px">
                        <a-input-number v-model="formData.useCount" :read-only="true" />
                    </a-form-item>
                    <a-form-item label="单价" field="price" label-col-flex="100px">
                        <a-input-number v-model="formData.price" :max="999999" @change="computeSumMoney" />
                    </a-form-item>
                    <a-form-item label="金额" field="sumMoney" label-col-flex="100px">
                        <a-input-number v-model="formData.sumMoney" :max="99999999" :read-only="true" />
                    </a-form-item>
                    <a-form-item label="预警数" field="warningCount" label-col-flex="100px">
                        <a-input-number v-model="formData.warningCount" />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>


<script lang="ts">
import { onMounted, reactive, ref } from 'vue';
import Toolbar from '@/components/Toolbar.vue';
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'
import pagination from "@arco-design/web-vue/es/pagination";
import { FormInstance } from "@arco-design/web-vue/es/form";

import { localeText } from '@/api/aggridZw'
import PageTabelLayout from "@/components/pageTabelLayout.vue";
import CheckboxCellRenderer from '@/hooks/checkboxCellRenderer.js';
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'

const localeTextData: any = ref(localeText);
const headerShow = ref<boolean>(true)


interface FirmEntity {
    firm: string,
    firmId: string,
}

interface MeterEntity {
    meterNo: string,
    meterName: string,
    meterId: string
}

export default {

    setup() {

        const meterList = ref<MeterEntity[]>([]);
        const firmList = ref<FirmEntity[]>([]);
        const isExpand = ref(true);

        const selectedKeys = ref([]);


        let searchData = reactive<{
            companyId: string,
            meterId: string,
            total: number | string,
            current: number,
            size: number
        }>({
            companyId: null,
            meterId: null,
            total: 10,
            current: 1,
            size: 10
        });



        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            departmentList: any[],
            pageLoading: boolean,
            headerShow: boolean
        }>({
            showAdd: false,
            sideTitle: "",
            departmentList: [],
            pageLoading: false,
            headerShow: true
        })

        const formData = reactive({
            meterId: null,
            meterNo: '',
            meterName: '',
            meterType: '',
            lastCount: null,
            thisCount: null,
            useCount: null,
            price: null,
            sumMoney: null,
            warningCount: null
        });

        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
        }

        const columnDefs = [
            {
                showRowGroup: 'hide_def',
                "headerName": "",
                "checkboxSelection": true,
                "headerCheckboxSelection": true,
                "pinned": "left",
                "width": 150,
                resizable: false,
                filter: false,
                sortable: false,
                minWidth: 50,
                maxWidth: 50,
                lockPosition: "left",
            },
            {
                headerName: 'ID',
                field: 'id',
                // pinned: o['fixed'],
                width: 160
            },
            {
                headerName: '设备编号',
                field: 'meterNo',
                width: 160
            },
            {
                headerName: '设备名称',
                field: 'meterName',
                width: 160
            },
            {
                headerName: '计数日期',
                field: 'createTime',
                width: 160
            },
            {
                headerName: '昨日读数',
                field: 'lastCount',
                editable: true,
                width: 160
            },
            {
                headerName: '今日读数',
                field: 'thisCount',
                editable: true,
                width: 160
            },
            {
                headerName: '使用数',
                field: 'useCount',
                valueGetter: params => {
                    params.data.useCount = params.data.thisCount - params.data.lastCount;
                    return params.data.useCount;
                },
                width: 160
            },
            {
                headerName: '单价',
                field: 'price',
                editable: true,
                width: 160
            },
            {
                headerName: '金额',
                field: 'sumMoney',
                valueGetter: params => {
                    params.data.sumMoney = params.data.price * params.data.useCount;
                    return params.data.sumMoney;
                },
                width: 160
            },
            {
                headerName: '预警数',
                field: 'warningCount',
                editable: true,
                width: 160
            }
        ]


        let tableDataList = ref([]);
        let gridOptions = ref();
        let departmentSelect = ref();

        const gridReady = (params: any) => {
            gridOptions = params.api;
        }

        const loadMeterSelect = () => {
            post({
                url: 'ems/energyMeter/findMeters',
                data: {}
            }).then(({ code, data }) => {
                if (code === 200) {
                    meterList.value = data
                }
            })
        }

        const loadConsumeList = () => {
            pageData.pageLoading = true;
            console.log(searchData.companyId);
            post({
                url: "ems/energyConsume/findPagedConsumes",
                data: searchData
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        console.log(gridOptions);
                        searchData.total = data.total;
                        gridOptions.setRowData(data.records);
                        tableDataList.value = data.records;
                    }
                });
        }



        const pageChange = (val: any) => {
            searchData.current = val;
            loadConsumeList();
        }

        onMounted(() => {
            loadMeterSelect();
            initData();
        })

        const initData = () => {
            post({
                url: 'ems/common/fetchUserInfoByToken',
                async: false,
                data: {}
            }).then(({ code, message, data }) => {
                if (code === 200) {
                    searchData.companyId = data.firmId;
                    loadConsumeList();
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }
            })
        }


        const showInsertForm = () => {
            pageData.showAdd = true;
            pageData.sideTitle = "新增能耗数据";
        };


        const formRef = ref<FormInstance>();
        const addEquipmentConsume = () => {
            let meter = meterList.value.find(item => item.meterNo === formData.meterNo);
            console.log(meter);
            formData.meterId = meter.id;
            formData.meterName = meter.meterName;
            formRef.value?.validate().then((err) => {
                if (!err) {
                    post({
                        url: "ems/energyConsume/saveConsume",
                        data: formData
                    }).then((res: any) => {
                        if (res.code === 200) {
                            formRef.value?.resetFields();
                            pageData.showAdd = false;
                            Message.success({
                                content: "新增成功",
                                duration: 5000,
                            });
                            //将列表重置为第一页
                            searchData.current = 1;
                            loadConsumeList();
                        }
                    });
                }
            });
        };


        const updateConsumeList = () => {
            console.log('---------------');
            console.log(tableDataList.value);
            post({
                url: "ems/energyConsume/batchUpdateConsumes",
                data: tableDataList.value
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        Message.success({
                            content: "数据更新成功",
                            duration: 5000,
                        });
                        //loadConsumeList();
                    }
                });
        }


        const deleteHandler = () => {
            let rowIds = gridOptions.getSelectedRows().map((item) => item.id)
            if (rowIds.length === 0) {
                Message.warning("请选择要删除的数据！");
                return;
            }
            Modal.confirm({
                title: "系统提示",
                content: "确认删除选中的数据?",
                onOk() {
                    post({
                        url: "ems/energyConsume/deleteConsumes",
                        data: rowIds,
                    }).then(({ code, data, message }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: "删除成功",
                                duration: 5000,
                            });
                            loadConsumeList();
                        }
                    });
                },
            });
        }


        const cellValueChange = (event) => {
            console.log(gridOptions);
            if (event.column.colId == 'lastCount' || event.column.colId == 'thisCount') {
                console.log(gridOptions.getSelectedRows());
                console.log(event.data.id);
            }
        }


        const computeUseCount = () => {
            formData.useCount = formData.thisCount - formData.lastCount;
            formData.sumMoney = formData.price * formData.useCount;
        }

        const computeSumMoney = () => {
            formData.sumMoney = formData.price * formData.useCount;
        }



        return {
            isExpand,
            pageChange,
            headerShow,
            meterList,
            departmentSelect,
            cellValueChange,
            formData,
            columnDefs,
            loadConsumeList,
            initData,
            updateConsumeList,
            tableDataList,
            defaultColDef,
            gridOptions,
            gridReady,
            computeUseCount,
            computeSumMoney,
            deleteHandler,
            showInsertForm,
            addEquipmentConsume,
            formRef,
            firmList,
            pageData,
            searchData,
            localeTextData,
        };
    },

    components: { PageTabelLayout, CheckboxCellRenderer, CorporateSectorCascader }

};
</script>

<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}
</style>
